package com.woniuxy.service.impl;

import com.woniuxy.dao.CartDao;
import com.woniuxy.dao.GoodsDao;
import com.woniuxy.pojo.Cart;
import com.woniuxy.pojo.Goods;
import com.woniuxy.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Author 罗蔚
 * @Date 2022/3/28 1:16
 * @Description TODO
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartDao cartDao;
    @Autowired
    private GoodsDao goodsDao;

    @Override
    public void joinCart(int uid, int gid, int nums) {
        Cart cart = cartDao.findByUidAndGid(uid, gid);

        //根据商品id查询价格
        Goods goods = goodsDao.findByid(gid);

        // 判断是不是第一次
        if (cart == null) {
            //第一次, 就新增
            Cart _cart = new Cart();
            _cart.setUserid(uid);
            _cart.setGoodsid(gid);
            _cart.setNums(nums);
            BigDecimal price = goods.getSalesprice().multiply(new BigDecimal(nums));
            _cart.setPrice(price);

            cartDao.add(_cart);


        } else {
            //不是第一次, 就修改
            //修改价格和数量
            int _nums =cart.getNums()+nums;
            cart.setNums(_nums);

            BigDecimal _price = goods.getSalesprice().multiply(new BigDecimal(_nums));
            cart.setPrice(_price);

            cartDao.update(cart);

        }
    }

    @Override
    public List<Cart> findAllByUid(int uid) {
        return cartDao.findAllByUid(uid);
    }

    @Override
    public void delete(int gid) {
        cartDao.delete(gid);
    }

    @Override
    public void updateNumsByGid(int uid, int gid, int nums) {
        Goods goods = goodsDao.findByid(gid);
        BigDecimal price = goods.getSalesprice().multiply(new BigDecimal(nums));

        cartDao.updateNumsByGid(uid, gid, nums, price);
    }
}
